<template>
  <div style="max-height: 80vh; overflow: auto; padding: 10px">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <!-- <el-row v-if="form.orderId">
        <el-col :span="12">
          <el-form-item label="单号" prop="orderId">
            <el-input
              v-model="form.orderId"
              placeholder="请输入单号"
              readonly
            />
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户" prop="clientName">
            <el-select
              style="width: 100%"
              v-model="form.clientName"
              clearable
              filterable
              placeholder="请选择客户"
              remote
              reserve-keyword
              :remote-method="getListClient"
              @change="handleClientChange"
              :disabled="
                form.state == 3 ||
                form.state == 4 ||
                form.state == 5 ||
                form.state == 6 ||
                form.state == 7
              "
            >
              <el-option
                v-for="item in clientList"
                :key="item.clientId"
                :label="item.clientName"
                :value="item.clientId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="联系电话" prop="telnum">
            <el-input
              v-model="form.telnum"
              placeholder="请输入联系电话"
              readonly
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="收货人" prop="consignee">
            <el-select
              style="width: 100%"
              v-model="form.consignee"
              clearable
              filterable
              placeholder="请选择收货人"
              remote
              reserve-keyword
              :remote-method="getAddressList"
              @change="handleAddressChange"
              :disabled="
                form.state == 3 ||
                form.state == 4 ||
                form.state == 5 ||
                form.state == 6 ||
                form.state == 7
              "
            >
              <el-option
                v-for="item in addressList"
                :key="item.deliveryAddressId"
                :label="item.name"
                :value="item.deliveryAddressId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收货地址" prop="deliveryAddress">
            <el-input
              v-model="form.deliveryAddress"
              placeholder="收货地址"
              readonly
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="配送方式" prop="deliveryMethod">
            <el-select
              v-model="deliveryMethod"
              placeholder="请选择配送方式"
              style="width: 100%"
              @change="changeDelivery"
              :disabled="
                form.state == 3 ||
                form.state == 4 ||
                form.state == 5 ||
                form.state == 6 ||
                form.state == 7
              "
            >
              <el-option
                v-for="item in companyList"
                :key="item.value"
                :label="item.name"
                :value="item.logisticsCompanyId"
              >
                <span style="float: left">{{ item.name }}</span>
                <span
                  style="
                    float: right;
                    text-align: right;
                    color: #8492a6;
                    font-size: 13px;
                  "
                >
                  {{
                    item.paymentMethod == 0
                      ? "寄付"
                      : item.paymentMethod == 1
                      ? "到付"
                      : "包邮"
                  }}</span
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="返利金" prop="isUsingRebate">
            <el-checkbox
              v-model="form.isUsingRebate"
              label="优先使用"
              :true-label="'1'"
              :false-label="'0'"
              :disabled="
                form.state == 3 ||
                form.state == 4 ||
                form.state == 5 ||
                form.state == 6 ||
                form.state == 7
              "
            ></el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="单据类型" prop="orderType">
            <!-- <el-input v-model="form.orderType" placeholder="请输入单据类型" /> -->
            <el-select
              v-model="form.orderType"
              placeholder="请选择单据类型"
              style="width: 100%"
              @change="changeOrderType"
              :disabled="
                form.state == 2 ||
                form.state == 3 ||
                form.state == 4 ||
                form.state == 5 ||
                form.state == 6 ||
                form.state == 7
              "
            >
              <el-option
                v-for="dict in dict.type.qb_order_state"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="账户金额">
            <div style="display: flex; flex-wrap: wrap">
              <span style="margin-right: 20px"
                >现金：{{ clientRow.attr2 ? clientRow.attr2 : 0 }}</span
              >
              <span style="margin-right: 20px"
                >返利金：{{ clientRow.attr1 ? clientRow.attr1 : 0 }}</span
              >
              <span style="margin-right: 20px"
                >墙布：{{ clientRow.attr4 ? clientRow.attr4 : 0 }}</span
              >
              <span>物料：{{ clientRow.attr7 ? clientRow.attr7 : 0 }}</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-hasRole="['money']">
        <el-col :span="12">
          <el-form-item label="财务备注" prop="financialNotes">
            <el-input
              v-model="form.financialNotes"
              placeholder="请输入备注"
              type="textarea"
              :rows="2"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="抹零" prop="pocketMoney">
            <el-input-number
              v-model="form.pocketMoney"
              placeholder="请输入抹零金额"
              @change="countTotalPrice"
              clearable
              :min="0"
              :precision="2"
              :disabled="
                form.state == 3 ||
                form.state == 4 ||
                form.state == 5 ||
                form.state == 6 ||
                form.state == 7
              "
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="notes">
            <el-input
              v-model="form.notes"
              placeholder="请输入备注"
              type="textarea"
              :rows="2"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="groupBtns">
      <el-button-group>
        <el-button
          type="primary"
          size="mini"
          @click.native="getAdd()"
          icon="el-icon-circle-plus-outline"
          v-if="!form.orderId"
        >
          添 加</el-button
        >
        <el-button
          type="primary"
          size="mini"
          @click.native="getGoodsAdd()"
          icon="el-icon-circle-plus-outline"
          v-if="!form.orderId || form.state == 1"
        >
          选 择</el-button
        >
        <el-button
          @click.native="delItem()"
          type="danger"
          size="mini"
          icon="el-icon-delete"
          :disabled="
            selRow.length == 0 ||
            form.isDelete == 1 ||
            form.state == 2 ||
            form.state == 3 ||
            form.state == 4 ||
            form.state == 5 ||
            form.state == 6 ||
            form.state == 7
          "
          >批 量 删 除</el-button
        >
      </el-button-group>
      <!-- 新增不显示，不知道价格计算不出来  v-if="form.orderId" -->
      <div class="priceInfo">
        <span class="totalPrice">订单总计:￥ {{ form.totalPrice }}</span>
        <div
          v-if="form.orderType == 'SA' || form.orderType == 'SO'"
          style="display: flex; align-items: center"
        >
          <span class="totalPrice">本单金额:￥ {{ form.price }}</span>
          <!-- <span>包装:￥{{ form.packingFee }}</span> -->
          <div style="margin-right: 8px">
            <label @click="packingFeeInputShow = !packingFeeInputShow"
              >包装:￥</label
            >
            <el-input-number
              v-if="packingFeeInputShow"
              v-model="form.packingFee"
              :min="0"
              :precision="0"
              :controls="false"
              size="mini"
              style="width: 60px"
              @change="changeTotalPriceFun(form)"
            ></el-input-number>
            <span v-else>{{ form.packingFee }}</span>
          </div>
          <div style="margin-right: 8px">
            <label @click="logisticsFeeInputShow = !logisticsFeeInputShow"
              >快递:￥</label
            >
            <el-input-number
              v-if="logisticsFeeInputShow"
              v-model="form.logisticsFee"
              :min="0"
              :precision="0"
              :controls="false"
              size="mini"
              style="width: 60px"
              @change="changeTotalPriceFun(form)"
            ></el-input-number>
            <span v-else>{{ form.logisticsFee }}</span>
          </div>
          <div style="margin-right: 8px">
            <label @click="zeroCutFeeInputShow = !zeroCutFeeInputShow"
              >零裁:￥</label
            >
            <el-input-number
              v-if="zeroCutFeeInputShow"
              v-model="form.zeroCutFee"
              :min="0"
              :precision="0"
              :controls="false"
              size="mini"
              style="width: 60px"
              @change="changeTotalPriceFun(form)"
            ></el-input-number>
            <span v-else>{{ form.zeroCutFee }}</span>
          </div>
        </div>

        <!-- <el-button-group>
          <el-button icon="el-icon-refresh-right"></el-button>
          <el-button icon="el-icon-info"></el-button>
        </el-button-group> -->
      </div>
    </div>

    <el-table
      ref="itemTable"
      v-loading="loading"
      :data="lst"
      :row-class-name="tableRowClassName"
      @selection-change="handleSelectionChange"
      @row-click="saveRow"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" label="ID" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="型号" align="center" width="180" prop="name">
        <template slot-scope="scope">
          <el-select
            v-if="scope.row.isEdit"
            style="width: 100%"
            v-model="scope.row.name"
            filterable
            placeholder="请选择型号"
            remote
            reserve-keyword
            :remote-method="getGoodsList"
            @change="handleGoods($event, scope.$index)"
          >
            <el-option
              v-for="item in goodsList"
              :key="item.productId"
              :label="item.name"
              :value="item.productId"
            >
            </el-option>
          </el-select>
          <span v-else>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单价" align="center" prop="price">
        <template slot-scope="scope">
          <div>
            <span style="font-size: 15px">{{ scope.row.price }}</span>
            <span v-if="scope.row.unit" style="font-size: 15px"
              >/{{ scope.row.unit }}</span
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="length">
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.length"
            size="small"
            placeholder="数量"
            @input="countTotalPrice(scope.row)"
          />
          <span v-else>{{ scope.row.length }}</span>
        </template>
      </el-table-column>
      <el-table-column label="高度" align="center" prop="height">
        <template slot-scope="scope">
          <div v-if="scope.row.unit == '平方米'">
            <el-input
              v-if="scope.row.isEdit"
              v-model="scope.row.height"
              size="small"
              placeholder="高度"
              @input="countTotalPrice(scope.row)"
            />
            <span v-else>{{ scope.row.height }}</span>
          </div>
          <div
            v-else-if="scope.row.unit == '幅' && scope.row.fabricType == '2'"
          >
            <el-input
              v-if="scope.row.isEdit"
              v-model="scope.row.height"
              size="small"
              placeholder="高度"
              @input="countTotalPrice(scope.row)"
            />
            <span v-else>{{ scope.row.height }}</span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="小计" align="center">
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.subtotal"
            size="small"
            placeholder="小计"
            @input="countsubTotalFun(scope.row)"
          />
          <span v-else style="font-size: 15px">{{ scope.row.subtotal }}</span>
        </template>
      </el-table-column>
      <el-table-column label="折扣" align="center">
        <template slot-scope="scope">
          <span style="font-size: 15px">{{
            scope.row.discount 
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工艺要求" align="center" prop="technology">
        <template slot-scope="scope">
          <el-select
            v-if="scope.row.isEdit"
            v-model="scope.row.technology"
            size="small"
            placeholder="工艺要求"
            style="width: 100%"
            @change="countTotalPrice()"
          >
            <el-option :label="'冷胶'" :value="0" />
            <el-option :label="'热胶'" :value="1" />
            <el-option :label="'先冷后热'" :value="3" />
            <el-option :label="'无工艺'" :value="2" />
          </el-select>
          <span v-else>{{ scope.row.technology | technologyFormat }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="变更状态"
        align="center"
        prop="variationStatus"
        min-width="80"
      ></el-table-column> -->
      <el-table-column label="备注" align="center" prop="remark" width="180">
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.remark"
            size="small"
            placeholder="备注"
          />
          <span v-else>{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="img" width="60">
        <template slot-scope="scope">
          <el-image
            class="goodsImg"
            style="width: 40px; height: 40px"
            :src="scope.row.img"
            :preview-src-list="[scope.row.img]"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
    </el-table>
    <el-form class="footFormContent" v-if="!!form.orderId">
      <el-row>
        <el-col :span="6">
          <el-form-item label="创建日期:">
            <span v-show="form.createTime">{{
              form.createTime | dateFormat
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="提交日期:">
            <span v-show="form.subTime">{{ form.subTime | dateFormat }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="初审日期:">
            <span v-show="form.approvedTime">{{
              form.approvedTime | dateFormat
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="审核时间:">
            <span v-show="form.financialApprovedTime">{{
              form.financialApprovedTime | dateFormat
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 选择货品 -->
    <el-dialog
      v-if="goodsVisible"
      title="墙布货品"
      :append-to-body="true"
      :visible.sync="goodsVisible"
      width="72vw"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <selGoods ref="selGoods" :multi="1" :orderType="form.orderType" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="selGoods()">确 定</el-button>
        <el-button @click="goodsVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { deletOrderItem, addOrderItem } from "@/api/qb";
import {
  region,
  getRegionName,
  getRegionId,
  shippingRates,
} from "@/utils/regions.js";
import { getAddressList } from "@/api/transport/shipAddress";
import { listCompany } from "@/api/transport/logistics";
import { getClient, listClient } from "@/api/mes/md/client";
import { getQbGoodsList } from "@/api/goods/qb";
import selGoods from "@/views/goods/qb/mods/select.vue";
export default {
  dicts: ["qb_order_state"],
  name: "RecordFormEdit",
  props: ["brandList"],
  components: { selGoods },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 表单参数
      form: {
        isUrgent: 0, //加急
        isUsingRebate: 0,
        productList: [],

        state: 1, // 1新建
        consignee: "",
        notes: "",
        deliveryAddress: "",
        deliveryAddressId: "",
        deliveryMethod: "",
        postageModeOfPayment: null,
        telnum: "",
        brandId: null,
        brandName: "",
        region: [],
        province: "", // 省份名称
        city: "", // 城市名称
        district: "", // 区名称
        orderType: "SA",
        packingFee: 0,
        logisticsFee: 0,
        zeroCutFee: 0,
        totalPrice: 0,
        clientId: null,
      },
      lst: [], //货品数据，防止污染
      copyList: [], //备份初始货品数据，判断是否修改
      goodsList: [],
      // 表单校验
      rules: {
        consignee: [
          { required: true, message: "请选择收货人", trigger: "blur" },
        ],
      },
      selRow: [], //勾选行row
      // 禁用今天以前的日期
      pickerOptions: {
        disabledDate(v) {
          return v.getTime() < new Date().getTime() - 86400000; //  - 86400000是否包括当天
        },
      },
      companyList: [], //物流公司
      addressList: [], //收货地址
      clientList: [], //查询客户信息
      clientRow: {}, //当前客户信息
      goodsVisible: false,
      deliveryMethod: null,
      zeroCutFeeInputShow: false,
      logisticsFeeInputShow: false,
      packingFeeInputShow: false,
    };
  },
  watch: {
    lst: function (val, oldVal) {
      if (val == undefined) {
        this.lst = [];
      }
      for (var i = 0; i < val.length; i++) {
        val[i].rownum = i;
      }
    },
  },
  mounted() {
    // 监听整个文档的点击事件
    document.addEventListener("click", this.handleDocumentClick);
    this.getAddressList(); //收货地址
    this.listCompany(); //物流公司
    this.getListClient(); //查询客户
    // console.log(this.form);
    // this.initDelivery(this.form.deliveryMethod);
  },
  beforeDestroy() {
    // 移除事件监听器
    document.removeEventListener("click", this.handleDocumentClick);
  },
  methods: {
    // 新增行
    getAdd() {
      var objRow = {
        isEdit: false,
        productId: null,
        technology: 2,
        height: "2.8",
        variationStatus: "",
        price: 0,
        unit: "",
        discount: 0,
        subtotal: 0,
        img: null,
      };
      if (!!this.form.orderId) {
        objRow.orderId = this.form.orderId;
      }
      this.lst.push(objRow);
    },
    getGoodsAdd() {
      this.goodsVisible = true;
      this.$nextTick(() => {
        this.$refs.selGoods.getList();
      });
    },
    selGoods() {
      const selListVal = this.$refs.selGoods.$refs.selectVal.selection;
      if (!selListVal.length) {
        // this.$mount
        this.$message.error("请选择要添加的单据！！");
        return;
      }
      for (var i = 0; i < selListVal.length; i++) {
        var item = selListVal[i];
        let objRow = {
          isEdit: false,
          productId: item.productId,
          unit: item.unit,
          technology: 2,
          height:
            item.unit == "平方米"
              ? item.productType
                ? item.productType
                : 2.8
              : 1,
          length: 0,
          variationStatus: "",
          name: item.name,
          price: item.price,
          fabricType: item.fabricType,
          img: item.img,
          discount: 0,
          subtotal: 0,
        };
        if (!!this.form.orderId) {
          objRow.orderId = this.form.orderId;
          addOrderItem(objRow).then((res) => {
            // this.$emit("handleUpdate", this.form);
            objRow.id = res.data;
            this.lst.push(objRow);
          });
        } else {
          this.lst.push(objRow);
        }
        // this.lst.push(objRow);
      }
      this.goodsVisible = false;
    },

    // 删除行
    delItem() {
      var that = this;
      this.$confirm("是否确认删除，此操作不可逆, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 执行删除的方法
          for (var i = 0; i < that.selRow.length; i++) {
            var indexI = that.selRow[i];
            fn: for (var j = 0; j < that.lst.length; j++) {
              var indexJ = that.lst[j];
              if (indexI.rownum == indexJ.rownum) {
                // 判断item是否为id
                if (!!indexJ.id) {
                  deletOrderItem(indexJ.id).then((res) => {
                    // this.$modal.msgSuccess("删除成功");
                    // this.$emit("handleUpdate", this.form);
                    this.countTotalPrice();
                  });
                }
                that.lst.splice(j, 1);
              }
            }
          }
        })
        .catch(() => {});
    },
    handleSelectionChange(val) {
      this.selRow = val;
    },
    // 行点击事件
    saveRow(row) {
      // 允许生产中修改
      if (
        // this.form.state == 3 ||
        this.form.state == 4 ||
        this.form.state == 5 ||
        this.form.state == 6 ||
        this.form.state == 7
      ) {
        return;
      }

      for (var i = 0; i < this.lst.length; i++) {
        this.$set(this.lst[i], "isEdit", false);
      }
      if (!row.isEdit) {
        this.$set(row, "isEdit", true);
      } else {
        this.$set(row, "isEdit", false);
      }
      this.$forceUpdate();
    },
    handleDocumentClick(event) {
      // 检查点击事件是否发生在表格外
      if (!this.$refs.itemTable.$el.contains(event.target)) {
        // 鼠标点击在表格外部,关闭编辑行
        for (var i = 0; i < this.lst.length; i++) {
          this.lst[i].isEdit = false;
        }
      }
    },
    // 物流公司
    listCompany() {
      listCompany().then((response) => {
        this.companyList = response.rows;
        // deliveryMethod
        this.initDelivery(this.form);
      });
    },
    // 初始化物流公司
    initDelivery(val) {
      var index = this.companyList.findIndex(
        (e) =>
          e.name == val.deliveryMethod &&
          e.paymentMethod == val.postageModeOfPayment
      );
      if (index != -1) {
        // this.deliveryMethodId = this.companyList[index].logisticsCompanyId;
        var way = "到付";
        if (this.companyList[index].paymentMethod == 2) {
          way = "包邮";
        } else if (this.companyList[index].paymentMethod == 0) {
          way = "寄付";
        }
        this.deliveryMethod = val.deliveryMethod + "(" + way + ")";
      }
    },
    changeDelivery(val) {
      var index = this.companyList.findIndex(
        (e) => e.logisticsCompanyId == val
      );
      if (index != -1) {
        this.form.deliveryMethod = this.companyList[index].name;
        this.form.deliveryMethodId = this.companyList[index].logisticsCompanyId;
        this.form.postageModeOfPayment = this.companyList[index].paymentMethod;
        var way = "到付";
        if (this.companyList[index].paymentMethod == 2) {
          way = "包邮";
        } else if (this.companyList[index].paymentMethod == 0) {
          way = "寄付";
        }
        this.deliveryMethod = this.companyList[index].name + "(" + way + ")";
        this.countTotalPrice();
      }
    },

    // 获取收货地址
    getAddressList(isDefault) {
      var queryParams = {
        pageNum: 1,
        pageSize: 100,
        clientId: this.form.clientId,
      };
      getAddressList(queryParams).then((response) => {
        this.addressList = response.rows;
        // 根据isDefault 判断是否开启默认选择
        if (!!isDefault) {
          for (let i = 0; i < this.addressList.length; i++) {
            const item = this.addressList[i];
            if (item.isDefault == 1) {
              this.handleAddressChange(item.deliveryAddressId);
            }
          }
        }
      });
    },
    // 获取当前客户信息
    // getClientList(val) {
    //   getClient(val).then((res) => {
    //     this.clientRow = res.data;
    //   });
    // },
    //
    handleAddressChange(val) {
      var index = this.addressList.findIndex((e) => e.deliveryAddressId == val);
      if (index != -1) {
        var item = this.addressList[index];
        this.form.consignee = item.name; //收货人
        this.form.deliveryAddressId = item.deliveryAddressId;
        this.form.deliveryAddress =
          item.province + item.city + item.district + item.address;
        this.form.province = item.province;
        this.form.city = item.city;
        this.form.district = item.district;
        this.form.region = getRegionId([
          this.form.province,
          this.form.city,
          this.form.district,
        ]);
        this.form.telnum = item.tel ? item.tel : this.form.telnum;
        this.countTotalPrice(); //计算价格
        // 信息
        if (!this.form.clientName) {
          this.form.clientName = item.clientName;
          this.form.clientId = item.clientId;
        }

        // this.getClientList(item.clientId); //获取选中的客户信息
      }
    },
    // 获取当前墙布货品信息
    getGoodsList(val) {
      var queryParams = {
        pageNum: 1,
        pageSize: 100,
        data: {
          name: val,
          namenum: null,
          fabricType: null,
          type: null,
          isuse: 1,
          typeNumber: null,
        },
      };
      // if (this.form.orderType == "") {
      //   // null
      // } else if (this.form.orderType == "SA") {
      //   queryParams.typeNumber = 1;
      // } else {
      //   queryParams.typeNumber = -1;
      // }
      getQbGoodsList(queryParams).then((res) => {
        this.goodsList = res.rows;
      });
    },
    handleGoods(val, rowIndex) {
      // console.log(val, rowIndex);
      var index = this.goodsList.findIndex((e) => e.productId == val);
      if (index != -1) {
        var item = this.goodsList[index];
        this.lst[rowIndex].name = item.name;
        this.lst[rowIndex].price = item.price;
        this.lst[rowIndex].productId = item.productId;
        this.lst[rowIndex].unit = item.unit;
        this.lst[rowIndex].fabricType = item.fabricType;
        this.lst[rowIndex].img = item.img;
      }
    },
    // 修改长度，重新计算金额
    countTotalPrice() {
      // 新增时不知道品名价格，计算不出来
      // if (!this.form.orderId) {
      //   return;
      // }
      var lengths = 0; //总长
      var eqlengths = 0;
      this.form.packingFee = 0;
      this.form.logisticsFee = 0;
      this.form.zeroCutFee = 0;
      this.form.totalPrice = 0;
      this.form.price = 0;
      for (var i = 0; i < this.lst.length; i++) {
        var item = this.lst[i];
        var len = !!item.length ? Number(item.length) : 0;
        var heights = !!item.height ? Number(item.height) : 0;
        // 判断除了绣花的加入长度
        if (item.fabricType != 2) {
          eqlengths += len;
        }
        lengths += len;

        // 小计
        if (item.fabricType == "2" && item.unit == "幅") {
          item.discount = 0;
          // item.subtotal = item.subtotal;
          this.form.price += Number(item.subtotal);
          // break;
        } else {
          // 本单总计 -四舍五入
          this.form.price += Number(
            (
              (Number(item.price) + (item.technology == 3 ? 8 : 0)) *
              len *
              heights
            ).toFixed(2)
          );
          item.subtotal = this.countPriceFun(item);
        }
      }
      // 长度不为0,计算 且是正常单据
      if (lengths != 0) {
        //  小于10米收30包装费，大于10米免包装费
        if (eqlengths < 10 && eqlengths != 0 && this.form.orderType == "SA") {
          this.form.packingFee += 30;
        }
        // 小于等于1米收10元零裁费，
        if (lengths < 1 && this.form.orderType == "SA") {
          this.form.zeroCutFee += 10;
        }
        this.form.price = this.form.price.toFixed(2);
        //运费
        if (this.form.orderType == "SA") {
          this.form.logisticsFee = this.calculateShippingCost(
            lengths,
            this.form.price
          );
        }
      }

      // 抹零计算
      this.form.totalPrice = Number(
        (
          this.totalPriceFun(this.form) -
          Number(this.form.pocketMoney ? this.form.pocketMoney : 0)
        ).toFixed(2)
      );
    },
    // 计算 订单总计form.totalPrice
    totalPriceFun(row) {
      var total = 0;
      total +=
        Number(row.price) +
        Number(row.zeroCutFee) +
        Number(row.packingFee) +
        Number(row.logisticsFee);
      return total.toFixed(2);
    },
    //修改包装、零裁、快递费
    changeTotalPriceFun(row) {
      var total = 0;
      total +=
        Number(row.price) +
        Number(row.zeroCutFee) +
        Number(row.packingFee) +
        Number(row.logisticsFee);
      this.form.totalPrice = Number(total.toFixed(2));
    },
    // 计算快递费
    calculateShippingCost(weights, totalValue) {
      const province = this.form.province; // 省份名称来自表单选择
      const weight = weights; // 计算总重量

      const rateval = shippingRates[province]; // 根据省份获取费率
      if (this.form.postageModeOfPayment != 0) {
        //0 寄付（计算）、1到付、2包邮
        return 0;
      }
      if (!rateval || weight == 0) {
        return 0; // 如果省份没有对应的费率，则返回0
      }
      let baseCost = 0; //基础运费
      let extraCost = 0; //超过30斤以上的续费

      if (weight <= 10) {
        baseCost = rateval.base10kg;
      } else if (weight <= 20) {
        baseCost = rateval.base20kg;
      } else if (weight <= 30 && weight > 20) {
        baseCost = rateval.base30kg;
      } else {
        baseCost = rateval.base30kg;

        if (weight > 30 && weight <= 100) {
          extraCost = (weight - 30) * rateval.over30kg;
        } else if (weight > 100 && weight <= 600) {
          extraCost =
            (100 - 30) * rateval.over30kg + (weight - 100) * rateval.over100kg;
        } else {
          extraCost =
            (100 - 30) * rateval.over30kg +
            (600 - 100) * rateval.over100kg +
            (weight - 600) * rateval.over600kg;
        }
        console.log(baseCost, weight);
        baseCost += extraCost;
      }

      let insuranceCost = 2; // 保价费起步价
      if (totalValue > 2000) {
        insuranceCost = totalValue / 1000;
      }
      return (baseCost + insuranceCost).toFixed(2);
    },
    changeOrderType() {
      if (this.form.orderId) {
        for (var i = 0; i < this.lst.length; i++) {
          var item = this.lst[i];
          deletOrderItem(item.id).then((res) => {
            console.log("切换类型，清空数据");
            // this.itemList.splice(i, 1);
          });
          if (i == this.lst.length - 1) {
            this.lst = [];
          }
        }
      } else {
        this.lst = [];
      }
      this.form.packingFee = 0;
      this.form.logisticsFee = 0;
      this.form.zeroCutFee = 0;
      this.form.totalPrice = 0;
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.variationStatus == "已变更") {
        return "warning-row"; //'success-row'
      }
      return "";
    },
    // 小计 计算
    countPriceFun(row) {
      var total = 0;
      if (!!row.price) {
        total = Number(
          (
            (Number(row.price) + (row.technology == 3 ? 8 : 0)) *
            Number(row.length) *
            Number(row.height) *
            (!row.discount ? 1 : Number(row.discount))
          ).toFixed(2)
        );
      }
      return total;
    },
    // 折扣
    countsubTotalFun(row) {
      // 计算本单金额和本单总计
      this.form.price = 0;
      for (var i = 0; i < this.lst.length; i++) {
        var item = this.lst[i];
        this.form.price += Number(item.subtotal);
      }
      this.form.price = this.form.price.toFixed(2);
      this.form.totalPrice = Number(
        (
          this.totalPriceFun(this.form) -
          Number(this.form.pocketMoney ? this.form.pocketMoney : 0)
        ).toFixed(2)
      );
      // 绣花 单位为幅的不计算折扣
      if (row.fabricType == "2" && row.unit == "幅") {
        row.discount = 0;
        return;
      }
      // 计算折扣
      var total = 0;
      if (!!row.price) {
        total = Number(
          (
            (Number(row.price) + (row.technology == 3 ? 8 : 0)) *
            Number(row.length) *
            Number(row.height)
          ).toFixed(2)
        );
      }
      row.discount = Number((Number(row.subtotal) / total).toFixed(2));
    },
    // 初始化，根据客户id查询
    initClient(val) {
      listClient({
        pageNum: 1,
        pageSize: 100,
        enableFlag: "Y",
        clientId: val,
      }).then(({ rows }) => {
        var index = rows.findIndex((a) => a.clientId == val);
        if (index != -1) {
          this.clientRow = rows[index];
        }
      });
    },
    // 切换客户
    handleClientChange(val) {
      var index = this.clientList.findIndex((a) => a.clientId == val);
      if (index != -1) {
        this.clientRow = this.clientList[index];
        this.form.clientName = this.clientList[index].clientName;
        this.form.clientId = this.clientList[index].clientId;
        this.form.telnum = this.clientList[index].tel;

        this.form.consignee = ""; //收货人
        this.form.deliveryAddressId = "";
        this.form.deliveryAddress = "";
        this.form.deliveryMethod = "";
        // 选择客户后重置收货人
        this.form.postageModeOfPayment = null;
        this.form.province = "";
        this.form.city = "";
        this.form.district = "";
        this.form.region = [];
        if (!this.deliveryMethodId) {
          this.deliveryMethodId = this.clientList[index].logisticsCompanyId;
          this.changeDelivery(this.clientList[index].logisticsCompanyId); //设置默认物流公司
        }
        this.getAddressList(true); //查询收货地址-默认收货人
      }
    },
    getListClient(clientName = "") {
      listClient({
        pageNum: 1,
        pageSize: 100,
        enableFlag: "Y",
        clientName,
      }).then(({ rows }) => {
        this.clientList = rows;
      });
    },
  },
  filters: {
    technologyFormat(data) {
      var str = "";
      switch (data) {
        case 0:
          str = "冷胶";
          break;
        case 1:
          str = "热胶";
          break;
        case 2:
          str = "无工艺";
          break;
        case 3:
          str = "先冷后热";
          break;
        default:
          break;
      }
      return str;
    },
    dateFormat(dataStr) {
      if (!dataStr) {
        return;
      }
      var dt = new Date(dataStr);
      var y = dt.getFullYear();
      var m = (dt.getMonth() + 1).toString().padStart(2, "0");
      var d = dt.getDate().toString().padStart(2, "0");
      var hh = dt.getHours().toString().padStart(2, "0");
      var mm = dt.getMinutes().toString().padStart(2, "0");
      var ss = dt.getSeconds().toString().padStart(2, "0");
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
    },
    discountFilt(val) {
      var value = 0;
      if (val >= 1 || !!val) {
        value = 0;
      } else {
        value = val;
      }
      return value;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-table .warning-row {
  background: oldlace;
}

::v-deep .el-table .success-row {
  background: #f0f9eb;
}
.groupBtns {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.priceInfo {
  cursor: default;
  display: flex;
  align-items: center;
  span {
    display: inline-block;
    margin: 0 8px;
  }
  label {
    font-weight: 400;
  }
  ::v-deep .el-input__inner {
    height: 25px !important;
    line-height: 24px !important;
  }
}
::v-deep .el-form-item {
  margin-bottom: 10px !important;
}
.footFormContent {
  margin-top: 10px;
  ::v-deep .el-form-item {
    margin-bottom: 0px;
  }
  ::v-deep .el-form-item__label,
  ::v-deep .el-form-item__content {
    line-height: 24px;
  }
}
::v-deep .image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}
</style>
